/**
 * 
 */
package fr.ema.arch3d.editor.mainGUI.listeners;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import org.jgraph.JGraph;
import org.jgraph.event.GraphSelectionEvent;
import org.jgraph.event.GraphSelectionListener;

import fr.ema.arch3d.editor.mainGUI.archExplorer.ArchTree;

/**
 * class description
 * 
 * @version    version 19 sept. 2009
 * @author     Huaxi (Yulin) ZHANG
 */

public class SyncGraphSelectionListener implements GraphSelectionListener {

    static ArchTree archTree;
    static JComponent paneGraph;
    static JGraph graphS, graphC, graphA;
    
    /**
     * Constructs...
     *
     *@param archTree
     *@param paneGraph2
     *@param graphS
     *@param graphC
     *@param graphA
     */
    public SyncGraphSelectionListener(ArchTree archTree, JComponent paneGraph2,
	    JGraph graphS, JGraph graphC, JGraph graphA) {
	this.archTree = archTree;
	this.paneGraph = paneGraph2;
	this.graphS = graphS;
	this.graphC = graphC;
	this.graphA = graphA;
    }

    public void valueChanged(GraphSelectionEvent e) {
        JViewport jvp       = (JViewport) paneGraph.getComponent(0);
        Object    selection = null;

        if (jvp.getView().getName().equals("graphS")) {
            selection = graphS.getSelectionModel().getSelectionCell();
        } else if (jvp.getView().getName().equals("graphC")) {
            selection = graphC.getSelectionModel().getSelectionCell();
        } else if (jvp.getView().getName().equals("graphA")) {
            selection = graphA.getSelectionModel().getSelectionCell();
        }

        if (selection==null)
             return;
        // clean the name of cell node without their type
        String a          = selection.toString();
        String selectName = null;

        if (a.contains(":")) {
            int p = a.indexOf(":");

            selectName = a.substring(0, p);
        } else {
            selectName = a;
        }

        // find the correspondent leaf in tree
        DefaultMutableTreeNode root, leaf;

        root = (DefaultMutableTreeNode) archTree.getModel().getRoot();
        leaf = root.getFirstLeaf();

        while (!selectName.equals((String) leaf.getUserObject())) {
            leaf = leaf.getNextLeaf();
        }

        // we set the corresponding tree selection
        archTree.setSelectionPath(new TreePath(leaf.getPath()));
    }
}
